package hderlis

import (
	"commodity-hub/cache"
	"commodity-hub/models"
	"commodity-hub/pkg"
	"encoding/json"
	"github.com/gin-gonic/gin"
	"strconv"
	"time"
)

func Login(c *gin.Context) {
	name := c.PostForm("name")
	passes := c.PostForm("passes")

	if name == "" || passes == "" {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "字段不能为空",
		})
		return
	}
	redis_key := "redis_login" + name
	po, _ := cache.Rdb.Get(cache.Ctx, redis_key).Int()
	if po >= 3 {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "密码错误3次，禁止登录",
		})
		return
	}
	var user models.User
	models.DB.Where("name=?", name).First(&user)
	if user.ID == 0 {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "用户不存在",
		})
		return
	}
	if user.Passes != pkg.Md5(passes) {
		cache.Rdb.Incr(cache.Ctx, redis_key)
		if po == 2 {
			cache.Rdb.Set(cache.Ctx, redis_key, 3, time.Hour*2)
			c.JSON(200, gin.H{
				"code": 500,
				"msg":  "密码错误3次封禁2小时",
			})
			return
		}
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "密码错误",
		})
		return
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "登录成功",
		"data": user,
	})
	return
}
func List(c *gin.Context) {
	page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
	size, _ := strconv.Atoi(c.DefaultQuery("size", "3"))
	offend := (page - 1) * size

	var count int64
	models.DB.Model(&models.Type{}).Count(&count)

	var list []models.Type

	redis_key := "redis_list" + strconv.Itoa(page)
	po, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if po == "" {
		models.DB.Offset(offend).Limit(size).Find(&list)
		marshal, _ := json.Marshal(list)
		cache.Rdb.Set(cache.Ctx, redis_key, marshal, time.Hour*2)
	} else {
		json.Unmarshal([]byte(po), &list)
	}

	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "查询成功",
		"data": gin.H{
			"count": count,
			"list":  list,
		},
	})
	return
}
func Lk(c *gin.Context) {

}
